<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'management:inFireAlarmInfo:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <div class="fireVeIm">
      <span style="margin-top: -170px;margin-left: -12px;">
          误报拍摄照片:
      </span>
      <div class="fireImg">
        <Image v-if="imageSrc" :src="imageSrc" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" alt="">
      </div>
    </div>
    <!-- 嵌入 BpmRuntimeTrace 组件 -->
    <BpmRuntimeTraceTimeLine
      :formKey="'equipment_fire_warning_process'"
      :bizKey="taskInfoId"
    />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="equipment_fire_warning_process"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'management:inFireAlarmInfo:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>

<script lang="ts" setup name="ViewsManagementInFireAlarmInfoForm">
  import { ref, unref, computed, reactive } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { InFireAlarmInfo, inFireAlarmInfoSave, inFireAlarmInfoForm } from '/@/api/management/inFireAlarmInfo';
  import { InFireNotificationData } from '/@/api/management/inFireNotification';
  import { BpmButton } from '/@/components/Bpm';
  import { Image } from 'ant-design-vue';
  import { Timeline, Collapse, CollapseItem } from 'ant-design-vue';
  import  BpmRuntimeTraceTimeLine  from '/@/components/Bpm/src/BpmRuntimeTraceTimeLine.vue'; // 引入 BpmRuntimeTrace 组件

  const imageSrc = ref('');
  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('management.inFireAlarmInfo');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InFireAlarmInfo>({} as InFireAlarmInfo);
  const loadingRef = ref(false);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增') : t('编辑'),
  }));

  const taskInfoId = ref('');
  const timelineData = ref([]);
  const equipmentStatusList = ref<any>({});

  const sortedTimelineData = computed(() => {
    return timelineData.value.slice().sort((a, b) => {
      return new Date(a.createTime).getTime() - new Date(b.createTime).getTime();
    });
  });

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('所属主体'),
      field: 'enterpriseName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('火情预警名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('建筑名称'),
      field: 'buildName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('区域名称'),
      field: 'regionIname',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('设备名称'),
      field: 'equipmentName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('预警时间'),
      field: 'alarmTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        disabled: true,
      },
    },
    {
      label: t('预警信息'),
      field: 'alarmInfo',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('反馈内容'),
      field: 'feedback',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
    {
      label: t('详细地址'),
      field: 'location',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await inFireAlarmInfoForm(data);
    console.log('inFireAlarmInfoForm res:', res);
    taskInfoId.value = res.inFireAlarmInfo.taskInfoId;
    record.value = (res.inFireAlarmInfo || {}) as InFireAlarmInfo;
    record.value.__t = new Date().getTime();
    imageSrc.value = record.value.fileUrl || '';
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      let data = await validate();
      data = {
        ...data,
        regionId: data.regionId,
        buildId: data.buildId,
        enterpriseId: data.enterpriseId,
      };
      formData(true, data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('表单验证错误:', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = event?.formData || (await validate());
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm);
      data.status = record.value.status;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      const res = await inFireAlarmInfoSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('提交数据错误:', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }


</script>

<style scoped lang="less"> 
.fireVeIm{
  display: flex;
  justify-content: space-start;
  align-items: center;
  margin-bottom: 5%;
  margin-left: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
}
</style>    